package com.shanghaiyimu.yimiyangche.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.shanghaiyimu.yimiyangche.R;
import com.shanghaiyimu.yimiyangche.mvplogin.ILoginPresenter;
import com.shanghaiyimu.yimiyangche.mvplogin.ILoginView;
import com.shanghaiyimu.yimiyangche.mvplogin.LoginPresenterImpl;

/**
 * MVP模式中View层对应一个activity，这里是登陆的activity
 */
public class LoginActivity extends AppCompatActivity implements ILoginView,View.OnClickListener{


    private EditText etUserName;
    private EditText etPassword;
    private ProgressDialog loginProgreess;

    private ProgressBar progressBar;
    private ILoginPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUserName = (EditText) findViewById(R.id.username);
        etPassword = (EditText) findViewById(R.id.password);
        findViewById(R.id.login).setOnClickListener(this);

        presenter = new LoginPresenterImpl(this);

    }


    @Override
    public void onClick(View v) {
        String username = etUserName.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        presenter.validateCredentials(username,password);
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        loginProgreess = ProgressDialog.show(this, "登录", "正在登录...");
    }

    @Override
    public void hideProgress() {
        loginProgreess.dismiss();
    }

    @Override
    public void setUsernameError() {
        etUserName.setError("账号出错");

    }

    @Override
    public void setPasswordError() {
        etPassword.setError("密码出错");
    }

    @Override
    public void navigateToHome() {
        Toast.makeText(this,"login success",Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra("name","李先生");
        this.setResult(0,intent);
        finish();
    }

    String BACK_CODE = "null";
    int BACK_CODE_NO = 99;
    @Override
    public void onBackPressed() {
        //数据是使用Intent返回
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra(BACK_CODE, BACK_CODE_NO);
        //设置返回数据
        this.setResult(RESULT_OK, intent);
        //关闭Activity
        this.finish();
    }
}
